<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getListData">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="listData" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection">
			</el-table-column>
			<el-table-column type="index" fixed>
			</el-table-column>
			<el-table-column prop="setMealName" label="套餐名"sortable>
			</el-table-column>
			<el-table-column prop="setMealPrice" label="套餐价格"sortable>
			</el-table-column>
			<el-table-column prop="expireDate" label="过期时间"sortable>
			</el-table-column>
			<el-table-column prop="status" :formatter="formatState" label="状态"sortable>
			</el-table-column>
			<el-table-column label="操作" fixed="right" width="160">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">购买</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="套餐名称" prop="setMealName">
					<el-input v-model="editForm.setMealName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="价格" prop="setMealPrice">
					<el-input v-model="editForm.setMealPrice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="过期日期" prop="expireDate">
					<el-input v-model="editForm.expireDate" auto-complete="off"></el-input>
					<el-date-picker
							v-model="editForm.expireDate"
							align="right"
							type="date"
							placeholder="选择日期"
							:picker-options="pickerOptions">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="editForm.status" placeholder="请选择状态">
						<el-option label="可用" value="1"></el-option>
						<el-option label="不可用" value="0"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="套餐名称" prop="setMealName">
					<el-input v-model="addForm.setMealName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="价格" prop="setMealPrice">
					<el-input v-model="addForm.setMealPrice" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="过期日期" prop="expireDate">
					<el-date-picker
							v-model="addForm.expireDate"
							align="right"
							type="date"
							placeholder="选择日期"
							:picker-options="pickerOptions">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="addForm.status" placeholder="请选择状态">
						<el-option label="可用" value="1"></el-option>
						<el-option label="不可用" value="0"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import util from '../../../common/js/util'
    //import NProgress from 'nprogress'
    //import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    export default {
        data() {
            return {
				pickerOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now();
					},
					shortcuts: [{
						text: '今天',
						onClick(picker) {
							picker.$emit('pick', new Date());
						}
					}, {
						text: '昨天',
						onClick(picker) {
							const date = new Date();
							date.setTime(date.getTime() - 3600 * 1000 * 24);
							picker.$emit('pick', date);
						}
					}, {
						text: '一周前',
						onClick(picker) {
							const date = new Date();
							date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
							picker.$emit('pick', date);
						}
					}]
				},
                filters: {
                    name: ''
                },
                listData: [],
                total: 0,
                keyword:'',
                pageSize: 10,
                currentPage:1,
                listLoading: false,
                sels: [],//列表选中列
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
					setMealName: [
						{ required: true, message: '请输入套餐名', trigger: 'blur' }
					],
					/*setMealPrice: [
						{ required: true, message: '请输入价格', trigger: 'blur'},
						//{ type: 'number', message: '请输入数字', trigger: 'blur'}
					]*/
                },
                //编辑界面数据
                editForm: {
					id: 0,
					setMealName: '',
					setMealPrice:'',
					expireDate:'',
					status:0,
                },

                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                addFormRules: {
					setMealName: [
						{ required: true, message: '请输入套餐名', trigger: 'blur' }
					],
					/*setMealPrice: [
						{ required: true, message: '请输入价格', trigger: 'blur'},
						//{ type: 'number', message: '请输入数字', trigger: 'blur'}
					]*/
                },
                //新增界面数据
                addForm: {
					id: 0,
					setMealName: '',
					setMealPrice:0,
					expireDate:'',
					status:0,
                }

            }
        },
        methods: {
            //状态显示转换
            formatState: function (row, column) {
                return row.status == 1 ? '可用' : row.status == 0 ? '不可用' : '未知';
            },
			//分页
            handleCurrentChange(val) {
                this.currentPage=val;
                this.getListData();
            },
            //获取用户列表
            getListData() {
                let para = {
                    currentPage: this.currentPage,
                    pageSize:this.pageSize,
                    keyword: this.filters.name
                };
                this.listLoading = true;
                this.$http.post('/setmeal/findByPage',para).then(res=>{
                    let ajaxResult =  res.data
                    if (ajaxResult.success){
                        this.listData = ajaxResult.data.result;
                        this.total = ajaxResult.data.total
                    }else {
                        this.$message({
                            message: '加载失败',
                            type: 'error'
                        });
                    }
                    this.listLoading = false;
                }).catch(error=>{
                    this.listLoading = false;
                    this.$message({
                        message: '加载失败',
                        type: 'error'
                    });
                })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    this.$http.delete('/setmeal/delete/'+row.id,{}).then(res=>{
                        let ajaxResult =  res.data
                        if (ajaxResult.success){
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getListData();
                        }else {
                            this.$message({
                                message: '删除失败,正有租户使用当前套餐',
                                type: 'error'
                            });
                        }
                        this.listLoading = false;
                    }).catch(error=>{
                        this.listLoading = false;
                        this.$message({
                            message: '删除失败，正有租户使用当前套餐',
                            type: 'error'
                        });
                    })

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
				this.$http.get('/setmeal/findById/'+row.id,{}).then(res=>{
					let ajaxResult = res.data
					console.log(res);
					console.log(ajaxResult)
					if (ajaxResult.success){
						this.editForm.setMealName = ajaxResult.data.setMealName;
						this.editForm.setMealPrice = ajaxResult.data.setMealPrice;
						this.editForm.expireDate = ajaxResult.data.expireDate;
						this.editForm.status = ajaxResult.data.status;

					}else {
						this.message({
							message:"获取失败",
							type:'error'
						})
					}
				}).catch(error=>{
					this.$message({
						message:"获取失败",
						type:'success'
					})
				})
            },
            //显示新增界面
            handleAdd: function () {
                this.addFormVisible = true;
                this.addForm = {

                };
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            this.$http.post("/setmeal/update",para).then(res =>{
                                let ajaxResult = res.data
                                if (ajaxResult.success){
                                    this.$message({
                                        message:"修改成功",
                                        type:'success'
                                    })
                                    this.$refs['editForm'].resetFields();
                                    this.editFormVisible = false;
                                    this.editLoading = false;
                                    this.getListData();
                                }else {
                                    this.message({
                                        message:"修改失败",
                                        type:'error'
                                    })

                                }
                            }).catch(error=>{
                                this.$message({
                                    message:"修改失败",
                                    type:'success'
                                })
                            })
                            /*para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            editUser(para).then((res) => {
                                this.editLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getListData();
                            });*/
                        });
                    }
                });
            },
            //新增
            addSubmit: function () {
                this.$refs.addForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            //准备参数，将参数拷贝到para中
                            let para = Object.assign({}, this.addForm);
                            this.$http.post('/setmeal/add',para).then(res =>{
                                let ajaxResult = res.data
                                if (ajaxResult.success){
                                    this.$message.success("保存成功");
                                    this.addFormVisible = false;
                                    this.$refs['addForm'].resetFields();
                                    this.getListData();
                                }else {
                                    this.addFormVisible = false;
                                    this.$message({
                                        message: '保存失败',
                                        type: 'error'
                                    });
                                }
                                this.addLoading = false;
                            }).catch(error =>{
                                this.addLoading = false;
                                this.$message({
                                    message: '保存失败',
                                    type: 'error'
                                });
                            })
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
            //批量购买
            batchRemove: function () {
                var ids = this.sels.map(item => item.id)
                this.$confirm('确认购买选中记录吗？', '提示', {
                    type: 'success'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    let para = { ids: ids };
                    this.$http.post("/setmeal/buySetMeal",para).then(res=>{
                        let ajaxResult = res.data;
                        if (ajaxResult.success){
                            this.$message({
                                message: '购买成功',
                                type: 'success'
                            });
                            this.getListData();
                        }else {
                            this.$message({
                                message: '购买失败,您所选套餐中包含已购买套餐',
                                type: 'error'
                            });
                        }
                        this.listLoading = false;
                    }).catch(error => {
                        this.listLoading = false;
                        this.$message({
                            message: '购买失败,您所选套餐中包含已购买套餐',
                            type: 'error'
                        });
                    })

                })
            }
        },
        mounted() {
            this.getListData();
        }
    }

</script>

<style scoped>

</style>